//
//  AddressBookHelper.m
//  青旅O2O
//
//  Created by qlwl on 16/5/18.
//  Copyright © 2016年 qlwl. All rights reserved.
//

#import "AddressBookHelper.h"
#import "UIAlertController+AlertController.h"



@interface AddressBookHelper ()

@end

@implementation AddressBookHelper

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    //1.获取授权状态
//    ABAuthorizationStatus type =  ABAddressBookGetAuthorizationStatus();
//    //授权申请
//    if (type == kABAuthorizationStatusNotDetermined) {
//        ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
//        ABAddressBookRequestAccessWithCompletion(book, ^(bool granted, CFErrorRef error) {
//            if (granted) {
//                NSLog(@"授权允许");
//            }else{
//                NSLog(@"授权拒绝");
//            }
//        });
//        //释放book
//        CFRelease(book);
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showInControllerWithCompletion:(HYBSuccessDictBlock)completion {
    //1.获取授权状态
    ABAuthorizationStatus type =  ABAddressBookGetAuthorizationStatus();
    //授权申请
    if (type == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
        ABAddressBookRequestAccessWithCompletion(book, ^(bool granted, CFErrorRef error) {
            if (granted) {
                NSLog(@"授权允许");
                [self openAddressBookWithCompletion:completion];
            }else{
                NSLog(@"授权拒绝");
            }
        });
        //释放book
        CFRelease(book);
    }else if(type == kABAuthorizationStatusAuthorized){
        //允许打开
        [self openAddressBookWithCompletion:completion];
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您未授权通讯录访问，请在设置里开启通讯录访问" preferredStyle:UIAlertControllerStyleAlert andCancelAction:^{
            
        } andOtherAction:^(int tag) {
            
        } cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
- (void)openAddressBookWithCompletion:(HYBSuccessDictBlock)completion
{
    _completionBlock = [completion copy];
    _pickerView = [[ABPeoplePickerNavigationController alloc] init];
    _pickerView.peoplePickerDelegate = self;
    [self presentViewController:_pickerView animated:YES completion:nil];
}

#pragma mark -  ABPeoplePickerNavigationControllerDelegate

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0

// Called after a person has been selected by the user.
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker
                         didSelectPerson:(ABRecordRef)person {
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    
    NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    if (firstName==nil) {
        firstName = @" ";
    }
    NSString *lastName=(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (lastName==nil) {
        lastName = @" ";
    }
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
        NSString *aPhone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMulti, i);
        [phones addObject:aPhone];
    }
    NSDictionary *dic = @{@"fullname": [NSString stringWithFormat:@"%@%@", firstName, lastName],
                          @"phone" : phones.count > 0 ? [phones firstObject] : @"读取失败"};
    
    _completionBlock(dic);
    [self dismissViewControllerAnimated:YES completion:nil];
    return;
}

// Called after a property has been selected by the user.
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker
                         didSelectPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier {
    _completionBlock(nil);
    [self dismissViewControllerAnimated:YES completion:nil];
    return;
}

#else

// Called after the user has pressed cancel.
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    _completionBlock(nil);
    [_targetController dismissViewControllerAnimated:YES completion:nil];
}


// Deprecated, use predicateForSelectionOfPerson and/or -peoplePickerNavigationController:didSelectPerson: instead.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    
    
    NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    if (firstName==nil) {
        firstName = @" ";
    }
    NSString *lastName=(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (lastName==nil) {
        lastName = @" ";
    }
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
        NSString *aPhone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMulti, i);
        [phones addObject:aPhone];
    }
    NSDictionary *dic = @{@"firstName": firstName,@"lastName":lastName,@"phones":phones};
    
    _completionBlock(dic);
    [_targetController dismissViewControllerAnimated:YES completion:nil];
    return NO;
}

// Deprecated, use predicateForSelectionOfProperty and/or -peoplePickerNavigationController:didSelectPerson:property:identifier: instead.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier {
    _completionBlock(nil);
    [_targetController dismissViewControllerAnimated:YES completion:nil];
    return NO;
}
#endif

#pragma mark - ABPersonViewControllerDelegate
// Called when the user selects an individual value in the Person view, identifier will be kABMultiValueInvalidIdentifier if a single value property was selected.
// Return NO if you do not want anything to be done or if you are handling the actions yourself.
// Return YES if you want the ABPersonViewController to perform its default action.
- (BOOL)personViewController:(ABPersonViewController *)personViewController
shouldPerformDefaultActionForPerson:(ABRecordRef)person
                    property:(ABPropertyID)property
                  identifier:(ABMultiValueIdentifier)identifier {
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    
    
    NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    if (firstName==nil) {
        firstName = @" ";
    }
    NSString *lastName=(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (lastName==nil) {
        lastName = @" ";
    }
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
        NSString *aPhone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMulti, i);
        [phones addObject:aPhone];
    }
    NSDictionary *dic = @{@"firstName": firstName,@"lastName":lastName,@"phones":phones};
    
    _completionBlock(dic);
    [self dismissViewControllerAnimated:YES completion:nil];
    return NO;
}


@end
